const router = require('koa-router')()
const { exec } = require('../utils/exec')
const { SuccessModel, FailModel } = require('../utils/resModel')
const { secret_code } = require('../utils/index')
const jwt = require('jsonwebtoken')
router.prefix('/blogs')

router.get('/get-test', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query
  try {
    const sql = `select * from blogs limit ? offset ?`
    const data = await exec(sql, [size * 1, (page - 1) * size])
    ctx.body = new SuccessModel('success', data)
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

// 查
router.get('/list', async (ctx, next) => {
  const { page = 1, size = 5 } = ctx.query

  // const { authorization } = ctx.request.headers
  try {
    // jwt.verify(authorization, secret_code)
    const sql = `select * from blogs limit ? offset ?`
    const data = await exec(sql, [size * 1, (page - 1) * size])
    ctx.body = new SuccessModel('success', data)
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 增
router.post('/list', async (ctx, next) => {
  const { title, content, userId } = ctx.request.body
  // const { authorization } = ctx.request.headers
  try {
    // jwt.verify(authorization, secret_code)
    const sql = `insert into blogs (title, content, userId) values (?, ?, ?)`
    const data = await exec(sql, [title, content, userId])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('fail')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

// 改
router.put('/list', async (ctx, next) => {
  const { title, content, blogId } = ctx.request.body
  // const { authorization } = ctx.request.headers
  try {
    // jwt.verify(authorization, secret_code)
    const sql = `update blogs set title=?, content=? where blogId = ?`
    const data = await exec(sql, [title, content, blogId])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('修改失败')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})
// 删
router.delete('/list', async (ctx, next) => {
  const { blogId } = ctx.query
  // const { authorization } = ctx.request.headers
  try {
    // jwt.verify(authorization, secret_code)
    const sql = `delete from blogs where blogId=?`
    const data = await exec(sql, [blogId])
    if (data.affectedRows) {
      ctx.body = new SuccessModel('success', data)
    } else {
      ctx.body = new FailModel('fail')
    }
  } catch (err) {
    ctx.body = new FailModel('fail', err)
  }
})

module.exports = router
